<template>
	<view class="chat">
    <!-- 顶部标题 -->
    <view class="topTabbar">
      <!-- 返回图标 -->
     <!-- <u-icon class="icon" name="arrow-left" size="20px" color="#000" @click="goback()"></u-icon> -->
      <!-- 取卖放的名称-->
      <view class="text">{{this.userinfo.nickName}}</view>
    </view>
		<scroll-view  :style="{height: `${windowHeight-inputHeight - 180}rpx`}"
		id="scrollview"
		scroll-y="true" 
		:scroll-top="scrollTop"
		class="scroll-view"
		>
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<!-- 自己发的消息 -->
					<view class="item self" v-if="item.fromUserId == userId" >
						<!-- 文字内容 -->
						<view class="content right">
						{{item.msgContent}}
						</view>
						<!-- 头像 -->
						<image class="avatar" :src="userinfo.nickName">
						</image>
					</view>
					<!-- 机器人发的消息 -->
<!-- 					<view class="item Ai" v-if  = "item.toId == sellerId"> -->
					<view class="item Ai" v-if="item.fromUserId == sellerId"  >
						<!-- 头像 -->     
						<image class="avatar" :src="item.image">
						</image>
						<!-- 文字内容 -->
						<view class="content left">
							{{item.msgContent}}
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight - 60}rpx`}">
        <view class="uni-textarea">
          <textarea v-model="chatMsg"
            maxlength="300"
            confirm-type="send"
            @confirm="handleSend"
            placeholder="快来聊天吧~"
            :show-confirm-bar="false"
            :adjust-position="false"
            @linechange="sendHeight"
            @focus="focus" @blur="blur"
           auto-height></textarea>
        </view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
	import { mapMutations,mapState } from 'vuex'
	export default{
		components: {},
		data() {
			return {
				//键盘高度
				keyboardHeight:0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
			//	 wsTaskId: null, // WebSocket实例
				//发送的消息
				chatMsg:"",
				sendText:{
					  fromUserId: this.userId,
					  toUserId: 0,
					  msgContent: '',
					  time: '',
				},
				messageObj:{
					toUserId: this.sellerId,
					fromUserId: this.userId,
					toImage: "/static/uni.png",
					lastMessage: '',
					time: '',
					toName: 'otherName',
				},
				//某个卖家的所有消息，包括收到的和发出去的
				//messageList: [],
				//发给某个卖家的所有消息
				msgList:[],
				sellerId: 0,
			}
		},
		updated(){
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		computed: {
			...mapState('m_user', ['userinfo']),
			...mapState('m_user', ['userId']),
			...mapState('m_dept', ['deptId']),
			...mapState('m_dept', ['dept']),
			...mapState('m_ws', ['wsTaskId']),
			...mapState('m_messagelist', ['messagelist']),
			windowHeight() {
			    return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight(){
				return this.bottomHeight+this.keyboardHeight
			}
		},
		onLoad(options){
			//this.sellerId=options.sellerId;
			this.sellerId=2;
			console.log("====="+this.messageList)
			 //this.initWebSocket();
			this.$store.dispatch('WEBSOCKET_INIT', `wss://campusstyle.site:8982/websocket/${this.userId}`)
			
			//this.$store.initWebSocket();
			uni.$on('websocket-data', this.handleWebsocketData);
			
			uni.onKeyboardHeightChange(res => {
				//这里正常来讲代码直接写
				//this.keyboardHeight=this.rpxTopx(res.height)就行了
				//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
				this.keyboardHeight = this.rpxTopx(res.height)
				if(this.keyboardHeight<0)this.keyboardHeight = 0;
			})
		},
		onUnload(){
			//离开页面时将聊天记录存到后端
			this.saveMessage();
			// uni.offKeyboardHeightChange()
			//this.closeWebSocket(); // 页面销毁时关闭WebSocket连接
		},
		methods: {
			...mapMutations('m_messagelist', ['updatMessagelistInfo']),
			//将聊天记录存储
			async saveMessage(){
				await uni.request({
				    url: this.baseUrl+'/api/mobileChat/addChatList',
				    data: this.msgList,
					method: 'POST',
				    header: {
				          // "Content-Type": "application/json",
				          "Content-Type": "application/x-www-form-urlencoded"
				        },
				    success: (res) => {
						this.array=res.data.data
				    },
					fail: (res) =>{
						if (res.statusCode !== 200) return uni.$showMsg()
					}
				});
			},
			handleWebsocketData(data) {
			      if(data==""){
			      	  return;
			        }
			        var jsonObj = JSON.parse(data);
					//不是卖加的id,就新开一个
			        if(jsonObj.fromUserId!=this.toUserId){
			      	  this.getLastMessage(jsonObj.toUserId,jsonObj.fromUserId,jsonObj.createTime,jsonObj.msgContent,jsonObj.toName)
					  return;
			        }
			        let obj = {
			      		msgContent: jsonObj.msgContent,
			      		image:"/static/uni.png",
			      		createTime: jsonObj.createTime,
			        }
			        
			      this.getLastMessage(jsonObj.toUserId,jsonObj.fromUserId,jsonObj.createTime,jsonObj.msgContent,jsonObj.toName)
			      this.msgList.push(jsonObj);
			 },
			goback() {
				uni.switchTab({
				url: "/pages/tutorship/tutorship"
				})
			},
			focus(){
				this.scrollToBottom()
			},
			blur(){
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px){
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = ( 750 / deviceWidth ) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight(){
				setTimeout(()=>{
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res =>{
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				},10)
			},
			// 滚动至聊天底部
			scrollToBottom(e){
				setTimeout(()=>{
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) =>{
						if(res[1].height > res[0].height){
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				},15)
			},
			// 发送消息
			handleSend() {
				//如果消息不为空
				if(!this.chatMsg||!/^\s+$/.test(this.chatMsg)){
					
					this.scrollToBottom();
					//发送到服务端
					this.sendMessage();
					this.chatMsg = '';
				}else {
					this.$modal.showToast('不能发送空白消息')
				}
			},
			 getCurrentTime() {
				  const now = new Date();
				  const year = now.getFullYear();
				  const month = (now.getMonth() + 1).toString().padStart(2, '0');
				  const day = now.getDate().toString().padStart(2, '0');
				  const hours = now.getHours().toString().padStart(2, '0');
				  const minutes = now.getMinutes().toString().padStart(2, '0');
				  const seconds = now.getSeconds().toString().padStart(2, '0');
				  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			
			// 初始化WebSocket连接
		   initWebSocket() {
			//  const wsUrl = `ws://127.0.0.1:8982/websocket/${this.userId}`; // 替换为你的WebSocket服务器URL
			//  this.wsTaskId = uni.connectSocket({  
			// 		  url: wsUrl,  
			// 		  success: () => {  
			// 			console.log('尝试连接 WebSocket');  
			// 		  },  
			// 		  fail: (err) => {  
			// 			console.error('WebSocket 连接失败:', err);  
			// 		  }  
			// });
			
			// 注册 WebSocket 打开事件  
			   uni.onSocketOpen((res) => {  
				 console.log('WebSocket 连接已打开', res);  
				 // 这里可以根据需要发送消息等  
			   }); 
		// 注册 WebSocket 消息接收事件  
			  uni.onSocketMessage((res) => { 
				  if(res.data==""){
					  return;
				  }
				  var jsonObj = JSON.parse(res.data);
				  if(jsonObj.fromUserId!=this.sellerId){
					  return;
				  }
				  let obj = {
						msgContent: jsonObj.msgContent,
						//userContent: "",
						image:"/static/uni.png",
						time: jsonObj.time,
				  }
				  
				this.getLastMessage(jsonObj.toUserId,jsonObj.fromUserId,jsonObj.time,jsonObj.msgContent,jsonObj.toName)
				this.msgList.push(obj);
				console.log('收到 WebSocket 消息:', res.data);
			  });  
		  
			  // 注册 WebSocket 错误事件  
			  uni.onSocketError((err) => {  
				console.error('WebSocket 发生错误:', err);  
			  });  
		  
			  // 注册 WebSocket 关闭事件  
			  /* uni.onSocketClose((res) => {  
				console.log('WebSocket 连接已关闭', res);  
				// 如果需要，可以在这里重新连接  
			  }); */
		   },
		   //最后一个消息
		  getLastMessage(fromUserId,toUserId,createTime,msgContent,toName,image){
			  let obj = {
				  fromUserId: this.fromUserId,
				  toUserId: 0,
				  lastMessage: "",
				  image:"/static/uni.png",
				  createTime: "",
				  toName: "",
			  }
			   //获取到当前消息，然后放到消息list中
			    obj.fromUserId=fromUserId;
			    obj.toUserId=toUserId;
			    obj.createTime= createTime;
			    obj.lastMessage=msgContent;
				obj.toName=toName;
				//如果收到的消息或者发出去的消息是之前没有收到的内容，就将这个消息记录
				const index = this.messagelist.findIndex(item => item.fromUserId === fromUserId&&item.toUserId===toUserId);
				  if (index !== -1) {
				    // 如果找到了对象，更新它
				    this.messagelist[index] =  obj ;
				  } else {
				    // 如果没有找到对象，就在数组中添加一个新对象
				    this.messagelist.push(obj);
				  }
				//对方的名字存在时放入数据
				if(toName){
					//messageListFilter.push(obj);
					this.updatMessagelistInfo( this.messagelist)
				}
				
			  
		   },
		
		   // 发送消息
		   sendMessage() {
				this.sendText.msgContent=this.chatMsg
				this.sendText.fromUserId=this.userId
				this.sendText.toUserId=this.sellerId
				this.sendText.time=this.getCurrentTime()
				this.sendText.toName=this.messageObj.toName
				console.log("发送消息")
					console.log(this.sendText)
				 if (this.wsTaskId) {
				   uni.sendSocketMessage({
						  data: JSON.stringify(this.sendText),
					 success: () => {
					   console.log('消息发送成功');
					   this.getLastMessage(this.sendText.fromUserId,this.sendText.toUserId,this.sendText.time,this.sendText.msgContent,this.sendText.toName,this.sendText.image)
					   this.msgList.push(this.sendText);
					 },
					 fail: () => {
					   console.error('消息发送失败');
					 },
				   });
				 }
		   },
		
		   // 关闭WebSocket连接
		   closeWebSocket() {
			 if (this.wsTaskId) {
			   uni.closeSocket({  
				 id: this.wsTaskId,  
				 success: () => {  
				   console.log('WebSocket 连接已关闭');  
				 }  
			   });  
			 } 
		   },
		}
	}
</script>
<style lang="scss" scoped>
	
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;
	
	view,button,text,input,textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}
 
	/* 聊天消息 */
	.chat {
     .topTabbar {
          width: 100%;
          // height: 90rpx;
          // line-height: 90rpx;
          display: flex;
          //margin-top: 80rpx;
          justify-content: space-between;
      
          .icon {
            margin-left: 20rpx;
          }
      
          .text {
            margin: auto;
            font-size: 16px;
            font-weight: 700;
          }
      
          .button {
            width: 10%;
            margin: auto 20rpx auto 0rpx;
          }
        }
		.scroll-view {
			::-webkit-scrollbar {
					    display: none;
					    width: 0 !important;
					    height: 0 !important;
					    -webkit-appearance: none;
					    background: transparent;
					    color: transparent;
					  }
			
			// background-color: orange;
			background-color: #F6F6F6;
			
			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;
				
				.self {
					justify-content: flex-end;
				}
				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;
 
					.right {
						background-color: $chatContentbgc;
					}
					.left {
						background-color: #FFFFFF;
					}
                    // 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}
 
					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}
 
					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}
 
					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						background: $sendBtnbgc;
						border-radius: 50rpx;
						overflow: hidden;
						
						image {
							align-self: center;
						}
 
					}
				}
			}
		}
 
		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 100rpx;
			background: #F4F5F7;
			transition: all 0.1s ease;
			
			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #fff;
				transition: all 0.1s ease;
			}
 
			.uni-textarea {
				padding-bottom: 70rpx;  
				textarea {
					width: 537rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #f1f1f1;
					border-radius: 40rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 74rpx;
					padding: 5rpx 8rpx;
          text-indent: 30rpx;
				}
			}
            
			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 76rpx;
				margin-left: 25rpx;
				width: 120rpx;
				height: 75rpx;
				background: #ed5a65;
				border-radius: 50rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}
	}
</style>